<?php
// +----------------------------------------------------------------------
// | Author: derek <693472824@qq.com> <http://www.bloveambition.com/>
// +----------------------------------------------------------------------

namespace Blovex4\Logic;

/**
 * 订单业务逻辑层
 *
 * @author derek <693472824@qq.com>
 */
class OrdersLogic extends BaseLogic {

    /**
     * 派单时，获取小哥列表
     * 1.自有团队成员；2.在用户预约时间点 前后一小时内 有空的小哥；
     */
    public function memberList($orderID = ''){
        
        $list = array();
        
        if(empty($orderID)){
            return $list;
        }
        
        $order = $this->find($orderID);
        
        //查询在符合条件时间内已经安排订单的小哥
        $orderMap['status'] = array('BETWEEN', '2,5');
        $orderMap['_string'] = ' (emergency=1 and appointment='.$order['appointment'].
                                ') OR (emergency=2 and create_time between '.(NOW_TIME - 3600).' and '.
                                (NOW_TIME + $order['delay'] * 60 + 3600).')';
        
        $orderModel = M('Orders');
        $workerIDList = $orderModel->where($orderMap)->getField('worker_id', true);
        //$tp = $orderModel->getLastSql();
        
        if(!empty($workerIDList)){
            $map['worker_id'] = array('not in', $workerIDList);
        }else{
            $map['worker_id'] = array('neq', $order['worker_id']);
        }
        
        //当前用户可管理站点
        $siteID = AdminLogic::getSite();
        
        if(!empty($siteID)){
            $map['site_id'] = $siteID;
        }
        
        //自有团队成员
        $map['member_type'] = '1';
        $map['status'] = '1';       //已注册成功的小哥
        
        $list = M('Worker')->where($map)->getField('worker_id,account,name');
    
        return $list;
    }
    
    /**
     * 
     */
    public function dispatch($orderID = '', $workerID = ''){
        
        if(empty($orderID) || empty($workerID)){
            
            return false;
        }
        
        //新下单或已接单（可转单）
        $map['status'] = array('in', '1,2,8');
        $map['order_id'] = $orderID;
        
        $model = M('Orders');
        $order = $model->where($map)->find();
        
        //发送推送消息
        if(!empty($order)){
            
            //指定小哥时，发送推送消息
            $workerMap['worker_id'] = $workerID;
            $workerModel = M('Worker');
            
            $worker = $workerModel->where($workerMap)->find();
            
            $data['worker_id'] = $workerID;
            $data['site_id'] = $worker['site_id'];
            $data['status'] = '8';
            
            //转单：小哥已接单；若未接单，则应为派单
            if(!empty($order['worker_id']) && $order['status'] == '2'){
                $map['worker_id'] = $order['worker_id'];
                $map['status'] = '2';
                
                $data['order_type'] = '4';
                $data['sender'] = empty($order['sender']) ? $order['worker_id'] : $order['sender'];
            }else{  //无人接单时，status 应该等于 1，避免并发
                $map['status'] = array('in', '1,8');
                $data['order_type'] = '3';
            }
            
            $result = $model->where($map)->save($data);
            
            //推送消息
            if(!empty($result)){
                
                $adminID = AdminLogic::is_login();
                
                $messageModel = M('Message');
                $msgData['worker_id'] = $workerID;
                $msgData['site_id'] = $worker['site_id'];
                $msgData['msg_type'] = $data['order_type'] == '3' ? '7' : '6';
                $msgData['order_id'] = $orderID;
                $msgData['create_time'] = NOW_TIME;
                $msgData['sender'] = $adminID;
                $msgData['receipt'] = '2';
                
                //将原来未回执消息设置为已回执，避免并发
                $messageModel->where(array('order_id'=>$orderID, 'msg_type'=>array('in', '4,5,6,7,8')))->setField('receipt', '1');
                $msgID = $messageModel->add($msgData);
                
                $extra['msg_type'] = $msgData['msg_type'];
                $extra['content'] = '';
                $extra['order_id'] = $orderID;
                $extra['order_no'] = $order['order_no'];
                $extra['emergency'] = $order['emergency'];
                $extra['appointment'] = $order['appointment'];
                $extra['delay'] = $order['delay'];
                
                api('Util/jPush', array($worker['account'], array(), $extra));
            }
        }
        
        return true;
    }
    
    /**
     * 下单
     */
    public function saveAction(){
        
        $data = I();
        
        $userID = M('User')->where(array('account'=>$data['account']))->getField('user_id');
        
        if(empty($userID)){
            return -1;
        }
        
        $orderLogic = D('Api/Orders', 'Logic');
        
        //-1时新增维修地址
        if($data['address_id'] == -1){
            
            $addressData['user_id'] = $userID;
            $addressData['contact'] = $data['contact'];
            $addressData['telphone'] = $data['telphone'];
            $addressData['province'] = $data['province'];
            $addressData['city'] = $data['city'];
            $addressData['district'] = $data['district'];
            $addressData['address'] = $data['address'];
            $addressData['latitude'] = $data['latitude'];
            $addressData['longitude'] = $data['longitude'];
            
            //$site = M('Site')->field('site_id,ROUND(6378.137*2*ASIN(SQRT(POW(SIN(('.$address['latitude']
            //        .'*PI()/180-latitude*PI()/180)/2),2)+COS('.$address['latitude'].'*PI()/180)*COS(latitude*PI()/180)*POW(SIN(('.$address['longitude']
            //        .'*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli')->order('juli')->find();
            
            $site = $orderLogic->getSite($addressData);
            
            $addressData['site_id'] = $site['site_id'];
            
            $addressID = M('UserAddress')->add();
        }else{
            $addressID = $data['address_id'];
        }
        
        $suffix = \Org\Util\String::randString(4, 1);
        $orderNo = substr($userID, 0, 1).substr(date('Ymd'), 2).$suffix;
        
        $orderData['user_id'] = $userID;
        $orderData['address_id'] = $addressID;
        $orderData['order_no'] = $orderNo;
        $orderData['detail_id'] = $data['detail_id'];
        
        //预约服务
        if(!empty($data['appointment'])){
            $orderData['appointment'] = GetMkTime($data['appointment']);
            $orderData['delay'] = '0';
            $orderData['emergency'] = '1';
        }else{
            $orderData['appointment'] = '0';
            $orderData['delay'] = $data['delay'];
            $orderData['emergency'] = '2';
        }
        
        $orderData['create_time'] = NOW_TIME;
        
        $workerModel = M('Worker');
        
        //未指定小哥
        if(empty($data['worker_id'])){
            $orderData['status'] = '1';
            
            $address = M('UserAddress')->where(array('address_id'=>$addressID))->find();
            
            $site = $orderLogic->getSite($address);
            $orderData['site_id'] = $site['site_id'];
            
            $workerMap['site_id'] = $site['site_id'];
            
            if($orderData['emergency'] == '2'){
                $workerMap['member_type'] = '1';
                
                $account = M('Worker')->where($workerMap)->getField('account', true);
                
            }
            
            $msgWorkerID = !empty($account) ? '1' : ($orderData['emergency'] == '2' ? '2' : '0');
            
            if(empty($account)){
                
                unset($workerMap['member_type']);
                
                $account = M('Worker')->where($workerMap)->getField('account', true);
            }
        }else{
            $orderData['order_type'] = '2';
            $orderData['worker_id'] = $data['worker_id'];
            $orderData['status'] = '8';
            
            //指定小哥时，记录订单所属站点，并发送推送消息
            $workerMap['worker_id'] = $orderData['worker_id'];
            $worker = $workerModel->where($workerMap)->find();
            
            $orderData['site_id'] = $worker['site_id'];
            $account = $worker['account'];
        }
        
        //客服下单时，记录客服 ID
        $adminID = AdminLogic::is_login();
        $orderData['admin_id'] = $adminID;
        
        $orderID = M('Orders')->add($orderData);
        
        if($orderID){

            //指定小哥时，记录订单所属站点，并发送推送消息
            
            $messageModel = M('Message');
            $msgData['worker_id'] = $orderData['status'] == '8' ? $orderData['worker_id'] : $msgWorkerID;
            $msgData['msg_type'] = $orderData['status'] == '8' ? '8' : '4';
            $msgData['site_id'] = $orderData['site_id'];
            $msgData['order_id'] = $orderID;
            $msgData['create_time'] = NOW_TIME;
            $msgData['sender'] = $adminID;
            $msgData['receipt'] = $orderData['status'] == '8' ? '2' : '1';
    
            $msgID = $messageModel->add($msgData);
    
            $extra['msg_type'] = $msgData['msg_type'];
            $extra['content'] = '';
            $extra['order_id'] = $orderID;
            $extra['order_no'] = $orderNo;
            $extra['emergency'] = $orderData['emergency'];
            $extra['appointment'] = $orderData['appointment'];
            $extra['delay'] = $orderData['delay'];
    
            api('Util/jPush', array($account, array(), $extra));
        }
        
        return true;
    }
    
}